package edu.jamestang.yeb.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import edu.jamestang.yeb.config.JwtTokenUtil;
import edu.jamestang.yeb.entity.Admin;
import edu.jamestang.yeb.entity.AdminRole;
import edu.jamestang.yeb.entity.Role;
import edu.jamestang.yeb.mapper.AdminRoleMapper;
import edu.jamestang.yeb.mapper.RoleMapper;
import edu.jamestang.yeb.util.AdminUtil;
import edu.jamestang.yeb.util.Resp;
import edu.jamestang.yeb.mapper.AdminMapper;
import edu.jamestang.yeb.service.AdminService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author JamesTang
 * @since 2021-12-13
 */
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements AdminService {

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private AdminRoleMapper adminRoleMapper;

    @Value("${jwt.tokenHead}")
    private String tokenHead;

    @Override
    public Resp login(String username, String password, String code, HttpServletRequest request) {

        String captcha = (String)request.getSession().getAttribute("captcha");

        if(StringUtils.isEmpty(code) || !captcha.equalsIgnoreCase(code)){
            return Resp.error("captcha error");
        }

        UserDetails userDetails = userDetailsService.loadUserByUsername(username);

        if(null == userDetails || !passwordEncoder.matches(password, userDetails.getPassword())){
            return Resp.error("Wrong password");
        }

        if(!userDetails.isEnabled()){
            return Resp.error("Account ban");
        }

        //Update security detail obj
        UsernamePasswordAuthenticationToken authenticationToken = new
                UsernamePasswordAuthenticationToken(userDetails,null, userDetails.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        String token = jwtTokenUtil.generateToken(userDetails);
        Map<String,String> tokenMap = new HashMap<>();
        tokenMap.put("token", token);
        tokenMap.put("tokenHead", tokenHead);

        return Resp.success("login successful",tokenMap);
    }

    @Override
    public Admin getAdminByUsername(String username) {
        return adminMapper.selectOne(new QueryWrapper<Admin>().eq("username",username).eq("enabled",true));
    }

    @Override
    public List<Role> getRoles(Integer adminId) {
        return roleMapper.getRoles(adminId);
    }

    @Override
    public List<Admin> getAllAdmins(String keyword) {
        return adminMapper.getAllAdmins(AdminUtil.getCurrentAdmin().getId(), keyword);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Resp updateAdminRole(Integer adminId, Integer[] rids) {

        adminRoleMapper.delete(new QueryWrapper<AdminRole>().eq("adminId",adminId));
        Integer result = adminRoleMapper.addAdminRole(adminId, rids);

        if (rids.length == result){
            return Resp.success("Update successful");
        }

        return Resp.error("Update fail");
    }

    @Override
    public Resp updateAdminPassword(String oldPass, String pass, Integer adminId) {

        Admin admin = adminMapper.selectById(adminId);
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        if (encoder.matches(oldPass,admin.getPassword())){
            admin.setPassword(encoder.encode(pass));
           if(1 == adminMapper.updateById(admin)){
               return Resp.success("Password has been changed");
           }
        }
        return Resp.error("Update failure");
    }

    @Override
    public Resp updateAdminUserFace(MultipartFile file, Integer id, Authentication authentication) {

        Admin admin = adminMapper.selectById(id);
        String userFace = "http://118.178.239.179:9000/yeb/"+ file.getOriginalFilename();
        admin.setUserFace(userFace);
        int result = adminMapper.updateById(admin);

        if(1 == result){
            Admin principal = (Admin)authentication.getPrincipal();
            principal.setUserFace(userFace);
            SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(
                    admin, null, authentication.getAuthorities()
            ));

            return Resp.success("Update successful",userFace);
        }

        return Resp.error("Update failure");
    }

}
